package com.hongawen.channel;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

import static com.hongawen.channel.utils.ByteBufferUtil.debugAll;

/**
 * @author hongawen
 * @version 1.0
 * @data 2025/4/30 8:56
 */
public class ScatteringRead {

    /**
     * 简介：多个byteBuffer组合读取一个文件的内容，适合已知每个内容的长度
     * 同理多个byteBuffer组合写入一个文件的内容，也是一样的，API将read调整为write即可。
     *
     * @param args .
     */
    public static void main(String[] args) {
        String filePath = System.getProperty("user.dir") + "/io/data.txt";
        try (RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "r");
             FileChannel channel = randomAccessFile.getChannel()
        ) {
            ByteBuffer buffer1 = ByteBuffer.allocate(5);
            ByteBuffer buffer2 = ByteBuffer.allocate(6);
            ByteBuffer buffer3 = ByteBuffer.allocate(4);
            ByteBuffer buffer4 = ByteBuffer.allocate(4);
            ByteBuffer buffer5 = ByteBuffer.allocate(5);
            channel.read(new ByteBuffer[]{buffer1, buffer2, buffer3, buffer4, buffer5});
            debugAll(buffer1);
            debugAll(buffer2);
            debugAll(buffer3);
            debugAll(buffer4);
            debugAll(buffer5);
            System.out.println(StandardCharsets.UTF_8.decode(buffer1));
            System.out.println(StandardCharsets.UTF_8.decode(buffer2));
            System.out.println(StandardCharsets.UTF_8.decode(buffer3));
            System.out.println(StandardCharsets.UTF_8.decode(buffer4));
            System.out.println(StandardCharsets.UTF_8.decode(buffer5));
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
